@{
	ViewData["Title"] = "完工单";
	Layout = "~/Views/Shared/_Layout.cshtml";
}

<style>
	.drag-handle { cursor: move; }
	
	/* 审批状态标签样式 */
	.layui-badge {
		display: inline-block;
		padding: 4px 8px;
		font-size: 12px;
		font-weight: normal;
		line-height: 1;
		color: #fff;
		text-align: center;
		white-space: nowrap;
		vertical-align: baseline;
		border-radius: 12px;
		min-width: 60px;
	}
	
	.layui-bg-blue {
		background-color: #1E9FFF !important;
	}
	
	.layui-bg-orange {
		background-color: #FFB800 !important;
		color: #333 !important;
	}
	
	.layui-bg-green {
		background-color: #5FB878 !important;
	}
	
	.layui-bg-red {
		background-color: #FF5722 !important;
	}
	
	.layui-bg-gray {
		background-color: #999 !important;
	}
	
	/* 分页样式 */
	.layui-table-page {
		margin-top: 20px;
		margin-bottom: 20px;
		padding: 20px 0;
		text-align: center;
		z-index: 100;
		position: relative;
	}

	.layui-laypage {
		display: inline-flex;
		align-items: center;
		gap: 5px;
		background: white;
		padding: 10px 20px;
		border-radius: 25px;
		box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
		z-index: 101;
		position: relative;
		margin: 10px 0;
	}

	.layui-laypage a,
	.layui-laypage span {
		padding: 8px 12px;
		border-radius: 20px;
		transition: all 0.3s ease;
		text-decoration: none;
		color: #666;
		font-weight: 500;
	}

	.layui-laypage a:hover {
		background: rgba(102, 126, 234, 0.1);
		color: #667eea;
		transform: translateY(-1px);
	}

	.layui-laypage .layui-laypage-curr {
		background: linear-gradient(135deg, #667eea, #764ba2);
		color: white;
		box-shadow: 0 3px 10px rgba(102, 126, 234, 0.3);
	}
</style>

<div class="layui-fluid" style="min-height: calc(100vh - 120px); overflow: visible;">
	<div class="layui-row layui-col-space15">
		<div class="layui-col-md12">
			<div class="layui-card" style="min-height: auto; overflow: visible;">
				<div class="layui-card-header">
					<h3>完工单</h3>
				</div>
				<div class="layui-card-body" style="padding-bottom: 60px;">
					<div class="search-container" style="margin-bottom:10px;">
						<input type="text" id="qWorkOrderCode" placeholder="工单编号" class="layui-input" style="display:inline-block;width:200px;margin-right:10px;" />
						<button class="layui-btn layui-btn-warm" onclick="openAdvancedSearch()"><i class="layui-icon layui-icon-slider"></i> 高级查询</button>
						<button class="layui-btn" onclick="loadData(1)"><i class="layui-icon layui-icon-search"></i> 查询</button>
						<button class="layui-btn layui-btn-primary" onclick="resetSearch()"><i class="layui-icon layui-icon-refresh"></i> 重置</button>
						<button class="layui-btn layui-btn-primary" onclick="showColumnSettings()"><i class="layui-icon layui-icon-set-fill"></i></button>
					</div>

					<div id="advancedSearchContainer" style="display:none;padding:16px 16px 0 16px;" onclick="event.stopPropagation()">
						<div style="margin-bottom:10px;">
							<label style="display:inline-block;width:90px;color:#666;">工序名称</label>
							<select id="qProcessName" class="layui-select" style="display:inline-block;width:260px;margin-right:10px;"><option value="">工序名称(全部)</option></select>
						</div>
						<div style="margin-bottom:10px;">
							<label style="display:inline-block;width:90px;color:#666;">申请人</label>
							<select id="qApplicantUserName" class="layui-select" style="display:inline-block;width:260px;margin-right:10px;"><option value="">申请人(全部)</option></select>
						</div>
						<div style="margin-bottom:10px;">
							<label style="display:inline-block;width:90px;color:#666;">流程状态</label>
							<select id="qStatus" class="layui-select" style="display:inline-block;width:260px;margin-right:10px;">
								<option value="">流程状态(全部)</option>
								<option value="发起">发起</option>
								<option value="处理中">处理中</option>
								<option value="通过">通过</option>
								<option value="驳回">驳回</option>
							</select>
						</div>
						<div style="margin-bottom:10px;">
							<label style="display:inline-block;width:90px;color:#666;">申请时间</label>
							<input type="text" id="qCreateTimeStart" placeholder="申请时间开始" class="layui-input" style="display:inline-block;width:220px;margin-right:10px;" />
							<input type="text" id="qCreateTimeEnd" placeholder="申请时间结束" class="layui-input" style="display:inline-block;width:220px;margin-right:10px;" />
						</div>
						<p style="margin:0 0 12px 90px;color:#999;">设置好条件后，点击下方“确定”即可查询。</p>
					</div>

					<!-- 列设置模态框 -->
					<div id="columnSettingsModal" style="display:none; padding:20px 30px 10px 10px;">
						<p style="background:#f2fdfb;padding:10px 15px;color:#009688;">拖动列名可调整表格列显示顺序</p>
						<table class="layui-table" style="margin:0;">
							<thead>
								<tr>
									<th style="width:40px;">#</th>
									<th>列名</th>
									<th style="width:100px;">是否显示</th>
								</tr>
							</thead>
							<tbody id="columnSettingsTBody"></tbody>
						</table>
					</div>

					<table class="layui-table" id="approvalTable">
						<thead>
							<tr id="completionHeaderRow">
								<th>工单</th>
								<th>工单编号</th>
								<th>工序名称</th>
								<th>工序编号</th>
								<th>审批状态</th>
								<th>审批人</th>
								<th>审批时间</th>
								<th>创建时间</th>
								<th>创建人</th>
								<th>修改人</th>
								<th>修改时间</th>
								<th>操作</th>
							</tr>
						</thead>
						<tbody id="approvalTBody"></tbody>
					</table>

					<div class="layui-table-page">
						<div id="completionPager"></div>
					</div>
				</div>
			</div>
		</div>
	</div>
</div>

@section Scripts {
	<script>
		const READ_API_URL = '@ViewBag.ReadApiUrl';
		const WRITE_API_URL = '@ViewBag.WriteApiUrl';
		const CURRENT_USER_ID = '@ViewBag.CurrentUserId';
		const TOKEN = '@ViewBag.Token';
		let pageIndex = 1;
		let pageSize = 30;
		let advLayerIndex = null;

		// 列配置（持久化到 localStorage）
		const COLUMN_KEY = 'completionColumnSettings';
		const defaultColumns = [
			{ field: 'workOrderCode',   title: '工单',       visible: true },
			{ field: 'workOrderNo',     title: '工单编号',   visible: true },
			{ field: 'processName',     title: '工序名称',   visible: true },
			{ field: 'processCode',     title: '工序编号',   visible: true },
			{ field: 'status',          title: '审批状态',   visible: true },
			{ field: 'auditUserName',   title: '审批人',     visible: true },
			{ field: 'completedTime',   title: '审批时间',   visible: true },
			{ field: 'createTime',      title: '创建时间',   visible: true },
			{ field: 'applicantUserName',title:'创建人',     visible: true },
			{ field: 'modifierName',    title: '修改人',     visible: true },
			{ field: 'modifyTime',      title: '修改时间',   visible: true },
			{ field: 'actions',         title: '操作',       visible: true }
		];
		
		// 自动检测并更新列配置
		let columnSettings = JSON.parse(localStorage.getItem(COLUMN_KEY) || 'null') || defaultColumns;
		// 检查是否缺少操作列，如果缺少则自动添加
		if(!columnSettings.find(col => col.field === 'actions')){
			columnSettings.push({ field: 'actions', title: '操作', visible: true });
			localStorage.setItem(COLUMN_KEY, JSON.stringify(columnSettings));
		}

		function applyColumnSettings(){
			const headerRow = $('#completionHeaderRow');
			headerRow.empty();
			columnSettings.forEach(function(col){ if(col.visible){ headerRow.append(`<th>${col.title}</th>`); } });
		}

		function showColumnSettings(){
			layui.use(['layer','form'], function(){
				const layer = layui.layer;
				const form = layui.form;
				const tbody = $('#columnSettingsTBody');
				tbody.empty();
				columnSettings.forEach(function(col){
					tbody.append(`<tr data-field="${col.field}">\n\t\t\t\t<td class="drag-handle layui-icon layui-icon-more-vertical"></td>\n\t\t\t\t<td>${col.title}</td>\n\t\t\t\t<td style="text-align:center;"><input type="checkbox" ${col.visible ? 'checked' : ''}></td>\n\t\t\t</tr>`);
				});

				function ensureSortable(callback){
					if(window.Sortable){ callback(); return; }
					$.getScript('https://cdn.jsdelivr.net/npm/sortablejs@1.15.0/Sortable.min.js', callback);
				}
				ensureSortable(function(){ new Sortable(tbody[0], { handle: '.drag-handle', animation: 150 }); });

				layer.open({
					type: 1,
					title: '设置',
					content: $('#columnSettingsModal'),
					area: ['460px','520px'],
					shade: 0,
					btn: ['确定','重置','取消'],
					btn1: function(index){
						const newSettings = [];
						$('#columnSettingsTBody tr').each(function(){
							const field = $(this).data('field');
							const col = columnSettings.find(c => c.field === field);
							col.visible = $(this).find('input[type="checkbox"]').is(':checked');
							newSettings.push(col);
						});
						columnSettings = newSettings;
						localStorage.setItem(COLUMN_KEY, JSON.stringify(columnSettings));
						applyColumnSettings();
						loadData(pageIndex);
						layer.close(index);
					},
					btn2: function(){
						localStorage.removeItem(COLUMN_KEY);
						columnSettings = JSON.parse(JSON.stringify(defaultColumns));
						layui.layer.msg('已重置为默认列');
						applyColumnSettings();
						loadData(1);
						return false;
					},
					success: function(){ form.render(); }
				});
			});
		}

		layui.use(['layer','laydate'], function(){
			var laydate = layui.laydate;
			window.layer = layui.layer;
			laydate.render({ elem: '#qCreateTimeStart', type: 'datetime' });
			laydate.render({ elem: '#qCreateTimeEnd', type: 'datetime' });
		});

		function openAdvancedSearch(){
			const layerRef = window.layer || (parent && parent.layer) || (top && top.layer);
			const $ = (window.layui && layui.$) || window.$ || window.jQuery;
			const $content = $ ? $('#advancedSearchContainer') : null;
			if(!layerRef){
				alert('页面组件未就绪，请稍后重试');
				return;
			}
			if(!$content || !$content.length){
				alert('高级查询容器未找到');
				return;
			}
			const originalParent = $content.parent();
			const nextSibling = $content.next();
			advLayerIndex = layerRef.open({
				type: 1,
				title: '高级查询',
				area: ['600px','420px'],
				shadeClose: true,
				shade: 0,
				content: $content,
				zIndex: 999999,
				btn: ['确定','清空条件'],
				yes: function(index){
					loadData(1);
					layerRef.close(index);
				},
				btn2: function(){ clearAdvancedFields(); return false; },
				end: function(){
					if(nextSibling && nextSibling.length){ $content.insertBefore(nextSibling); } else { $content.appendTo(originalParent); }
					$content.hide();
				}
			});
		}

		function clearAdvancedFields(){
			$('#qProcessName').val('');
			$('#qApplicantUserName').val('');
			$('#qStatus').val('');
			$('#qCreateTimeStart').val('');
			$('#qCreateTimeEnd').val('');
		}

		function resetSearch(){
			$('#qWorkOrderCode').val('');
			clearAdvancedFields();
			loadData(1);
		}

		// 加载工序名称下拉
		async function loadProcessNames(){
			const url = `${READ_API_URL}/Process/names`;
			try{
				const resp = await fetch(url, { method: 'GET' });
				if(!resp.ok){ layer.msg('加载工序名称失败', {icon:2}); return; }
				const result = await resp.json();
				if(result.code !== 200){ layer.msg(result.msg || '加载工序名称失败', {icon:2}); return; }
				const list = Array.isArray(result.data) ? result.data : [];
				const sel = document.getElementById('qProcessName');
				sel.innerHTML = '<option value="">工序名称(全部)</option>';
				for(const item of list){
					const opt = document.createElement('option');
					opt.value = item.processName;
					opt.textContent = item.processName;
					sel.appendChild(opt);
				}
			}catch(err){
				console.error(err);
				layer.msg('加载工序名称接口异常', {icon:2});
			}
		}

		// 加载申请人下拉（需要Token）
		async function loadApplicants(){
			const url = `${READ_API_URL}/Account/GetAccountPage?Index=1&Size=1000`;
			try{
				const resp = await fetch(url, { headers: { 'Authorization': `Bearer ${TOKEN}` } });
				if(!resp.ok){ layer.msg('加载申请人失败', {icon:2}); return; }
				const result = await resp.json();
				if(result.code !== 200){ layer.msg(result.msg || '加载申请人失败', {icon:2}); return; }
				const list = Array.isArray(result.pageData) ? result.pageData : [];
				const sel = document.getElementById('qApplicantUserName');
				sel.innerHTML = '<option value="">申请人(全部)</option>';
				for(const item of list){
					const display = item.realName || item.name || '';
					if(!display) continue;
					const opt = document.createElement('option');
					opt.value = display;
					opt.textContent = display;
					sel.appendChild(opt);
				}
			}catch(err){
				console.error(err);
				layer.msg('加载申请人接口异常', {icon:2});
			}
		}

		function buildQuery(index){
			const params = new URLSearchParams();
			params.set('PageIndex', index || pageIndex);
			params.set('PageSize', pageSize);
			const w = $('#qWorkOrderCode').val().trim(); if(w) params.set('WorkOrderCode', w);
			const p = $('#qProcessName').val().trim(); if(p) params.set('ProcessName', p);
			const a = $('#qApplicantUserName').val().trim(); if(a) params.set('ApplicantUserName', a);
			const s = $('#qStatus').val(); if(s) params.set('Status', s);
			const t1 = $('#qCreateTimeStart').val().trim(); if(t1) params.set('CreateTimeStart', new Date(t1).toISOString());
			const t2 = $('#qCreateTimeEnd').val().trim(); if(t2) params.set('CreateTimeEnd', new Date(t2).toISOString());
			// 注释掉当前审批人条件，显示所有完工单
			// params.set('CurrentAuditUserId', CURRENT_USER_ID);
			return params.toString();
		}

		async function loadData(index){
			if(index) pageIndex = index;
			const url = `${READ_API_URL}/Approval/GetPendingApprovals?${buildQuery(pageIndex)}`;
			try{
				const resp = await fetch(url);
				if(!resp.ok){ layer.msg('查询失败', {icon:2}); return; }
				const result = await resp.json();
				if(result.code !== 200){ layer.msg(result.msg || '查询失败', {icon:2}); return; }
				renderTable(result.data.data || []);
				renderPager(result.data.totalCount || 0, result.data.pageIndex || pageIndex, result.data.pageSize || pageSize);
			}catch(err){
				console.error(err);
				layer.msg('请求异常', {icon:2});
			}
		}

		function renderTable(rows){
			const tbody = $('#approvalTBody');
			tbody.empty();
			if(!rows.length){
				const colspan = columnSettings.filter(c => c.visible).length || 1;
				tbody.append(`<tr><td colspan="${colspan}" style="text-align:center;color:#999;">暂无数据</td></tr>`);
				return;
			}
			for(const r of rows){
				let rowHtml = '<tr>';
				columnSettings.forEach(function(col){
					if(!col.visible) return;
					if(col.field === 'actions'){
						// 只有待审批状态才显示审批按钮
						if(r.status === '发起' || r.status === '处理中'){
							rowHtml += `<td>
								<button class="layui-btn layui-btn-xs layui-btn-normal" onclick="openApprovalDialog(${r.id || 0}, '${safe(r.workOrderCode)}')">
									<i class="layui-icon layui-icon-ok"></i> 审批
								</button>
							</td>`;
						} else {
							rowHtml += `<td>-</td>`;
						}
					} else if(col.field === 'status'){
						// 审批状态显示为标签样式
						rowHtml += `<td>${formatStatusTag(r[col.field])}</td>`;
					} else if(col.field === 'completedTime' || col.field === 'createTime' || col.field === 'modifyTime'){
						rowHtml += `<td>${formatTime(r[col.field])}</td>`;
					} else {
						rowHtml += `<td>${safe(r[col.field])}</td>`;
					}
				});
				rowHtml += '</tr>';
				tbody.append(rowHtml);
			}
		}

		function renderPager(total, index, size){
			// 使用Layui分页组件
			layui.use('laypage', function () {
				var laypage = layui.laypage;
				laypage.render({
					elem: 'completionPager',
					count: total,
					curr: index,
					limit: size,
					limits: [10, 20, 30, 50, 100],
					layout: ['count', 'prev', 'page', 'next', 'limit', 'skip'],
					theme: '#667eea',
					jump: function (obj, first) {
						if (!first) {
							pageIndex = obj.curr;
							pageSize = obj.limit;
							loadData(pageIndex);
						}
					}
				});
			});
		}

		function formatTime(v){ if(!v) return ''; try{ return new Date(v).toLocaleString(); }catch{ return v; } }
		function safe(v){ return (v ?? '').toString().replace(/</g,'&lt;').replace(/>/g,'&gt;'); }
		
		// 格式化审批状态为标签样式
		function formatStatusTag(status) {
			if (!status) return '';
			
			const statusConfig = {
				'发起': { class: 'layui-bg-blue', text: '发起' },
				'处理中': { class: 'layui-bg-orange', text: '处理中' },
				'通过': { class: 'layui-bg-green', text: '通过' },
				'驳回': { class: 'layui-bg-red', text: '驳回' },
				'审核通过': { class: 'layui-bg-green', text: '审核通过' },
				'审核未通过': { class: 'layui-bg-red', text: '审核未通过' },
				'已完成': { class: 'layui-bg-green', text: '已完成' },
				'已结束': { class: 'layui-bg-gray', text: '已结束' }
			};
			
			const config = statusConfig[status] || { class: 'layui-bg-gray', text: status };
			return `<span class="layui-badge ${config.class}">${config.text}</span>`;
		}

		// 打开审批对话框
		function openApprovalDialog(workflowInstanceId, workOrderCode){
			if(!workflowInstanceId){
				layer.msg('工作流实例ID不能为空', {icon:2});
				return;
			}
			
			layui.use(['layer','form'], function(){
				const layer = layui.layer;
				const form = layui.form;
				
				const content = `
					<div style="padding:20px;">
						<div class="layui-form">
							<div class="layui-form-item">
								<label class="layui-form-label">工单编号</label>
								<div class="layui-input-block">
									<input type="text" value="${workOrderCode}" readonly class="layui-input layui-disabled">
								</div>
							</div>
							<div class="layui-form-item">
								<label class="layui-form-label">操作类型</label>
								<div class="layui-input-block">
									<select id="operationType" lay-verify="required">
										<option value="">请选择操作类型</option>
										<option value="通过">通过</option>
										<option value="驳回">驳回</option>
									</select>
								</div>
							</div>
							<div class="layui-form-item layui-form-text">
								<label class="layui-form-label">审批意见</label>
								<div class="layui-input-block">
									<textarea id="comment" placeholder="请输入审批意见" class="layui-textarea" style="min-height:80px;"></textarea>
								</div>
							</div>
							<div class="layui-form-item">
								<label class="layui-form-label">步骤名称</label>
								<div class="layui-input-block">
									<input type="text" id="stepName" value="审批关尾" class="layui-input">
								</div>
							</div>
						</div>
					</div>
				`;
				
				layer.open({
					type: 1,
					title: '审批操作',
					content: content,
					area: ['500px', '400px'],
					btn: ['确定', '取消'],
					yes: function(index){
						const operationType = document.getElementById('operationType').value;
						const comment = document.getElementById('comment').value.trim();
						const stepName = document.getElementById('stepName').value.trim();
						
						if(!operationType){
							layer.msg('请选择操作类型', {icon:2});
							return;
						}
						if(!comment){
							layer.msg('请输入审批意见', {icon:2});
							return;
						}
						if(!stepName){
							layer.msg('请输入步骤名称', {icon:2});
							return;
						}
						
						processApproval(workflowInstanceId, operationType, comment, stepName, index);
					},
					success: function(){
						form.render();
					}
				});
			});
		}

		// 处理审批
		async function processApproval(workflowInstanceId, operationType, comment, stepName, layerIndex){
			const url = `${WRITE_API_URL}/Approval/ProcessApproval`;
			const params = {
				WorkflowInstanceId: workflowInstanceId,
				OperationType: operationType,
				Comment: comment,
				AuditUserName: '@ViewBag.CurrentUserName' || '当前用户',
				AuditUserId: parseInt(CURRENT_USER_ID) || 0,
				StepName: stepName
			};
			
			try{
				const resp = await fetch(url, {
					method: 'POST',
					headers: {
						'Content-Type': 'application/json',
						'Authorization': `Bearer ${TOKEN}`
					},
					body: JSON.stringify(params)
				});
				
				if(!resp.ok){
					layer.msg('网络请求失败', {icon:2});
					return;
				}
				
				const result = await resp.json();
				if(result.code === 200){
					layer.msg(result.msg || '审批操作成功', {icon:1});
					layer.close(layerIndex);
					// 刷新数据
					loadData(pageIndex);
				} else {
					layer.msg(result.msg || '审批操作失败', {icon:2});
				}
			}catch(err){
				console.error('审批操作异常:', err);
				layer.msg('审批操作异常', {icon:2});
			}
		}

		// 初始加载
		(async function(){
			applyColumnSettings();
			await Promise.all([
				loadProcessNames(),
				loadApplicants()
			]);
			loadData(1);
		})();
	</script>
} 